<template>
  <div class="container">
    <Breadcrumb :items="['menu.org', 'menu.org.department']" />
    <a-card class="general-card" :title="$t('menu.org.department')">
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="addHandler">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('department.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('department.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('department.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
        </a-col>
      </a-row>
      <!-- expandable hide-expand-button-on-empty -->
      <a-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        :size="size"
        :pagination="false"
      >
        <!-- <template #expand-icon>
          <icon-right />
        </template> -->
        <!-- <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template> -->
        <template #operations="{ record }">
          <a-button
            v-permission="['admin']"
            type="text"
            size="small"
            @click="addSubHandler(record)"
          >
            {{ $t('department.columns.operations.create') }}
          </a-button>
          <a-button
            v-permission="['admin']"
            type="text"
            size="small"
            @click="editHandler(record)"
          >
            {{ $t('department.columns.operations.edit') }}
          </a-button>
          <a-popconfirm
            content="确认删除该项?"
            type="warning"
            @before-ok="(done) => deleteHandler(done, record)"
          >
            <a-button v-permission="['admin']" type="text" size="small">
              {{ $t('department.columns.operations.delete') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <OrgInfo
      v-model:visible="dialogVisible"
      :title="optTitle"
      :form="selectDept"
      @refresh="search"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import {
    getOrgs,
    OrgServiceRecord,
    OrgRecord,
    SelectDept,
    deleteOrg,
  } from './api';
  import OrgInfo from './components/org-info.vue';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<OrgRecord[]>([]);

  const size = ref<SizeProps>('medium');

  const dialogVisible = ref(false);
  const optTitle = ref('新增');
  const emptyDept = {
    id: '',
    parentId: '',
    name: '',
    entName: '',
    parentName: '',
    pathName: '',
    pathNo: '',
  };
  const selectDept = ref<SelectDept>({ ...emptyDept });

  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    // {
    //   title: t('department.columns.index'),
    //   dataIndex: 'index',
    //   slotName: 'index',
    // },
    {
      title: t('department.columns.name'),
      dataIndex: 'name',
      // align: 'left',
      headerCellStyle: {
        textAlign: 'left',
      },
    },
    {
      title: t('department.columns.abbr'),
      dataIndex: 'entName',
      align: 'center',
      width: 260,
    },
    {
      title: t('department.columns.operations'),
      dataIndex: 'operations',
      slotName: 'operations',
      align: 'center',
      width: 260,
    },
  ]);
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data }: { data: OrgServiceRecord[] } = await getOrgs();
      renderData.value = tranferTreeData(data);
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const tranferTreeData = (data: OrgServiceRecord[]) => {
    const result: OrgRecord[] = [];
    data.forEach((item) => {
      const { children, content, id, parentId } = item;
      const obj: OrgRecord = {
        id,
        parentId,
        content,
        name: content.name,
        entName: content.entName,
      };
      if (children && children.length) {
        const childrenRes = tranferTreeData(children);
        obj.children = childrenRes;
      }
      result.push(obj);
    });
    return result;
  };

  const search = () => {
    fetchData();
  };

  fetchData();

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  // 打开新增组织机构弹窗
  const addHandler = () => {
    dialogVisible.value = true;
    optTitle.value = '新增';
    selectDept.value = { ...emptyDept, operator: 'add' };
  };

  // 打开新增子部门弹窗
  const addSubHandler = (record: OrgRecord) => {
    dialogVisible.value = true;
    optTitle.value = '新增子部门';
    selectDept.value = {
      id: '',
      name: '',
      entName: '',
      parentId: record.id,
      pathName: record.content?.pathName,
      pathNo: record.content?.pathNo,
      parentName: record.content?.name,
      operator: 'addSub',
    };
  };

  // 打开编辑组织机构弹窗
  const editHandler = (record: OrgRecord) => {
    dialogVisible.value = true;
    optTitle.value = '编辑';
    selectDept.value = {
      id: record.id,
      name: record.content?.name,
      entName: record.content?.entName,
      parentId: record.parentId,
      content: record.content,
      operator: 'edit',
    };
  };

  // 删除组织机构
  const deleteHandler = async (done: any, record: OrgRecord) => {
    const id = record.content?.id || '';
    await deleteOrg(id);
    search();
    done();
  };
</script>

<script lang="ts">
  export default {
    name: 'Department',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
